//
// Created by Administrator on 2024/5/6.
// 双链表结点增,减,查找
//

#include "linkedListUtil.h"

using namespace std;

bool insertDLinkedList(DNode *head, int v, int index)
{
    DNode *cur = head->next;
    for (int i = 0; i < index; ++i)
    {
        if (cur->next == nullptr)
            return false;
        cur = cur->next;
    }
    DNode *t = new DNode{v, cur, cur->next};
    // 执行插入
    if (cur->next != nullptr)
        cur->next->pre = t;
    // 这句话要写在后头
    cur->next = t;
    return true;
}

bool delDLinkedList(DNode *head, int index)
{
    DNode *cur = head->next;
    for (int i = 0; i < index; ++i)
    {
        if (cur->next == nullptr)
            return false;
        cur = cur->next;
    }
    cur->pre->next = cur->next;
    if (cur->next != nullptr)
        cur->next->pre = cur->pre;
    else
        cur->pre->next = nullptr;
    return true;
}

int searchDLinkedList(DNode * head, int v)
{
    int index = 0;
    DNode *cur = head->next;
    while(cur)
    {
        if(cur->v==v)
            return index;
        ++index;
        cur=cur->next;
    }
    return -1;
}
int main()
{
    vector<int> l{1, 2, 3, 4, 5, 6};
    DNode *h = Dbuild(l);
    printDLinkedList(h);
    cout << "insert:" << insertDLinkedList(h, 9, 5) << endl;
    printDLinkedList(h);
    cout << "delete:" << delDLinkedList(h, 6) << endl;
    printDLinkedList(h);
    cout<<"count_times:"<<searchDLinkedList(h,1)<<endl;
    return 0;
}